<template>
  <dtDialog
    :title="textMap[dialogStatus]"
    :visible.sync="compartmentVisible"
    :is-loading="loading"
    @closeDialog="resetCompartment"
    @comfirmBtn="submit"
  >
    <el-form
      ref="compartmentDataForm"
      slot="content"
      :rules="compartmentRules"
      :model="compartmenData"
      label-position="right"
      label-width="110px"
    >
      <el-form-item ref="areaParentIdRef" label="上级区划名称" prop="areaParentId">
        <dt-zoningCascader v-if="compartmentVisible" ref="dtZoningCascaderRef" v-model="compartmenData.areaParentId"
                           :is-echo="echo" @change="areaChange($event)" />
      </el-form-item>
      <el-form-item ref="areaParentCodeRef" label="上级区划代码" prop="areaParentCode">
        <el-input v-model.trim="compartmenData.areaParentCode" disabled />
      </el-form-item>
      <el-form-item label="区划代码" prop="areaCode">
        <el-input v-model.trim="compartmenData.areaCode" maxlength="12" placeholder="请输入区划代码"
                  class="limit" />
      </el-form-item>
      <el-form-item label="区划名称" prop="areaName">
        <el-input v-model.trim="compartmenData.areaName" maxlength="20" placeholder="请输入区划名称"
                  class="limit" />
      </el-form-item>
      <el-form-item label="区划层级" prop="areaLevel">
        <el-radio-group v-model="compartmenData.areaLevel">
          <el-radio v-for="item in remarkList" :key="item.dictCode" :label="item.dictCode"
                    @change="remarkChange">{{ item.dictName }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.trim="compartmenData.sort" :oninput="initPositiveInteger()" show-word-limit
                  maxlength="8" class="limit" />
      </el-form-item>
      <el-form-item label="备注" prop=" remark">
        <el-input v-model.trim="compartmenData.remark" :autosize="{ minRows: 4, maxRows: 4}" maxlength="200"
                  show-word-limit type="textarea" placeholder="请输入"
                  class="limit" />
      </el-form-item>
    </el-form>
  </dtDialog>
</template>
<script>
import
configApi
from '@/framework/api/zoningManage'
import { positiveInteger } from '@/framework/utils/validate'

export default {
  data() {
    const areaParentIdRule = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择上级区划名称'))
      } else {
        callback()
      }
    }
    return {
      echo: false,
      textMap: {
        update: '修改区划',
        create: '新增区划'
      },
      compartmentVisible: false,
      compartmentRules: {
        areaParentId: [
          { required: true, trigger: 'change', validator: areaParentIdRule }
        ],
        areaParentCode: [
          { required: true, message: '请先选择上级区划名称', trigger: 'change' }
        ],
        areaCode: [
          { required: true, message: '请输入区划代码', trigger: 'change' },
          { pattern: /^[0-9]*$/, message: '请输入数字' }
        ],
        areaName: [
          { required: true, message: '请输入区划名称', trigger: 'change' }
        ],
        areaLevel: [
          { required: true, message: '请选择区划层级', trigger: 'change' }
        ]
      },
      compartmenData: {
        areaParentId: '',
        areaParentCode: '',
        areaCode: '',
        areaName: '',
        areaLevel: '',
        sort: '',
        remark: ''
      },
      dialogStatus: '',
      remarkList: [],
      loading: false
    }
  },
  watch: {
    compartmentVisible(val) {
      if (val) {
        if (this.echo === false) {
          this.$nextTick((res) => {
            this.$refs.dtZoningCascaderRef.initData()
          })
        }
      }
    }
  },
  mounted() {
  },
  methods: {
    // 获取字典表
    getDictList() {
      const params = {
        dictTypeCode: 'area_level'
      }
      configApi.getDictList(params).then((res) => {
        this.remarkList = res.data
      })
    },
    // 改变上级区划
    areaChange(e) {
      const arrCode = e.areaCodePath
      switch (arrCode.length) {
        case 1:
          this.compartmenData.areaLevel = '1'
          break
        case 2:
          this.compartmenData.areaLevel = '2'
          break
        case 3:
          this.compartmenData.areaLevel = '3'
          break
        case 4:
          this.compartmenData.areaLevel = '4'
          break
        case 5:
          this.compartmenData.areaLevel = '5'
          break
        default:
          this.compartmenData.areaLevel = '6'
          break
      }
      // const arrName = e.areaNamePath
      this.compartmenData.areaParentCode = arrCode[arrCode.length - 1]
    },
    resetCompartment() {
      this.compartmenData = {
        areaParentId: '',
        areaParentCode: '',
        areaCode: '',
        areaName: '',
        areaLevel: '',
        sort: '',
        remark: ''
      }
      this.$nextTick(() => {
        this.$refs['areaParentIdRef'].clearValidate()
        this.$refs['areaParentCodeRef'].clearValidate()
      })
    },
    async handleData(row, type) {
      this.getDictList()
      if (type === 'add') {
        this.dialogStatus = 'create'
        this.echo = false
        this.compartmenData.areaParentId = ''
      } else {
        this.dialogStatus = 'update'
        this.echo = true
        configApi.detail({ areaId: row.areaId }).then(({ data }) => {
          this.compartmenData = data.area
          this.handleEchoData(data.treeNodeList, row)
        })
      }
      this.compartmentVisible = true
      await this.$nextTick()
      this.resetCompartment()
      this.$refs['compartmentDataForm'].clearValidate()
    },
    // 新增下级
    addData(row) {
      if (row.areaLevel === '5') {
        this.$dtMessage({
          type: 'error',
          message: '超出区划层级'
        })
        return
      }
      this.getDictList()
      this.dialogStatus = 'create'
      this.echo = true
      this.compartmentVisible = true
      this.$nextTick(() => {
        this.$refs['compartmentDataForm'].clearValidate()
      })
      configApi.queryHigherLevel({ areaCode: row.areaCode }).then(({ data }) => {
        switch (row.areaLevel) {
          case '1':
            this.compartmenData.areaLevel = '2'
            break
          case '2':
            this.compartmenData.areaLevel = '3'
            break
          case '3':
            this.compartmenData.areaLevel = '4'
            break
          default:
            this.compartmenData.areaLevel = '5'
            break
        }
        this.handleEchoData(data, row)
      })
    },
    // 处理反显
    handleEchoData(data, row) {
      const arr = []
      // 反显级联选择
      const obj = [{
        areaCode: '0',
        areaName: '根节点',
        children: data
      }]

      this.$refs.dtZoningCascaderRef.cascaderData = obj
      this.handleDealTreeData(data, arr)
      if (this.dialogStatus === 'create') {
        arr.push(row.areaCode)
        this.compartmenData.areaParentCode = row.areaCode
      }
      arr.unshift('0')
      this.compartmenData.areaParentId = arr.join(',')
    },
    // 处理areaPath
    handleDealTreeData(data, arr) {
      data.forEach((res) => {
        if (res.children && res.children.length > 0) {
          arr.push(res.areaCode)
          this.handleDealTreeData(res.children, arr)
        }
      })
    },

    submit() {
      this.$refs.compartmentDataForm.validate((valid) => {
        if (valid) {
          this.loading = true
          try {
            if (this.dialogStatus === 'create') {
              const data = Object.assign({}, this.compartmenData)
              // var obj = data.areaParentId.split(',')
              // if (obj.length > 5) {
              //   this.$dtMessage({
              //     message: '超出区划层级',
              //     type: 'error'
              //   })
              //   return
              // }
              configApi.add(data).then((res) => {
                this.compartmentVisible = false
                this.$parent.getList(this.compartmenData.areaParentCode)
                this.$message.success('新增成功')
              })
            } else {
              const data = Object.assign({}, this.compartmenData)
              configApi.update(data).then((res) => {
                this.compartmentVisible = false
                this.$parent.getList(this.compartmenData.areaParentCode)
                this.$message.success('修改成功')
              })
            }
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
    initPositiveInteger(data) {
      return positiveInteger(data)
    },
    remarkChange() {}
  }
}
</script>
